package 多线程.线程安全链表;

public class MyBlockQueue<T> {
    private int tail;
    private int head;
    private int size;
    String[] elems;

    public MyBlockQueue(){
        elems =new String[8];
    }
    public MyBlockQueue(int num){
        elems =new String[num];
    }

    //put添加方法
    public void put(String elem) throws InterruptedException {
        synchronized(this){
            //wait要搭配while使用
            while(size >= elems.length){
                //队列满了后续处理
                this.wait();
            }
            elems[tail] = elem;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;

            this.notify();
        }

    }
    public String take() throws InterruptedException{
        synchronized(this){
            if(size == 0){
                //队列空阻塞
                this.wait();
            }
            String result = elems[head];
            head++;
            if(head >= elems.length){
                head = 0;
            }
            size--;
            this.notify();
            return result;
        }
    }
}
